<template>
  <common-header page-title="商品详情" />
  <div class="detail-container">
    <el-card v-if="!loading && product" class="product-detail-card" :class="{ 'disabled': product.stock <= 0 }">
      <h2>{{ product.name }}</h2>

      <!-- 商品信息 -->
      <div class="product-info">
        <p><strong>单价:</strong> ¥{{ product.price }}/{{ product.unit }}</p>
        <p><strong>商品描述:</strong> {{ product.description }}</p>
        <p><strong>库存:</strong> {{ product.stock }}件</p>
        <p><strong>销量:</strong> {{ product.sales }}件</p>
        <p><strong>来源地:</strong> {{ product.origin }}</p> <!-- ✅ 确保这里用了 origin -->
      </div>

      <!-- 图片 -->
      <div class="product-image">
        <img :src="product.imageUrls" alt="商品图片" />
      </div>

      <!-- 购买按钮 -->
      <div class="action-buttons">
        <el-button type="success" round icon="ShoppingCart" @click="buyNow" :disabled="product.stock <= 0">立即购买</el-button>
        <el-button type="warning" round icon="ShoppingCart" @click="addToCart" :disabled="product.stock <= 0">加入购物车</el-button>
      </div>
    </el-card>

    <el-skeleton v-else :rows="6" animated />
    <div v-if="product && product.stock <= 0" class="out-of-stock-overlay">该商品已售罄</div>
  </div>
  <back-button />
</template>


<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import request from '@/utils/request'
import CommonHeader from '@/views/user/support/components/CommonHeader.vue'
import BackButton from '@/views/user/support/components/BackButton.vue'


const route = useRoute()
const router = useRouter()
const productId = route.params.id

const product = ref({
  name: '',
  description: '',
  price: 0,
  stock: 0,
  unit: '',
  origin: '',     // 新增 origin 字段
  imageUrls: '',
  sales: 0
})


const loading = ref(true)
const imageLoaded = ref(false)

const addToCart = async () => {
  const cartAddDto = {
    productId: product.value.id,
    quantity: 1
  };

  try {
    const res = await request.post('/api/v1/cart/add', cartAddDto);
    if (res.code === 2000) {
      ElMessage.success('已加入购物车');
    } else {
      alert('加入购物车失败：' + (res.msg || '未知错误'));
    }

  } catch (err) {
    console.error('网络异常:', err);
    alert('网络异常，请检查后端服务是否启动');
  }
}


const fetchProduct = async () => {
  try {
    const res = await request.get(`/api/v1/government/private/product/${productId}`)

    if (res.code === 2000 && res.data) {
      product.value = res.data
    } else {
      alert('获取商品失败：' + (res.msg || '未知错误'))
    }

  } catch (err) {
    console.error('网络异常:', err)
    alert('网络异常，请检查后端服务是否启动')
  } finally {
    loading.value = false
  }
}

const handleImageLoad = () => {
  imageLoaded.value = true
}

const buyNow = () => {
  router.push({ name: 'OrderConfirm', params: { id: productId } })
}

onMounted(() => {
  fetchProduct()
})
</script>


<style scoped>
.detail-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}
.product-detail-card.disabled {
  opacity: 0.6;
  pointer-events: none;
}

.out-of-stock-overlay {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 1.2rem;
  color: #999;
  z-index: 10;
}


.product-detail-card {
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  background-color: #fff;
  padding: 20px;
  transition: all 0.3s ease-in-out;
}

.product-detail-card:hover {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.product-info {
  font-size: 16px;
  color: #333;
  margin-bottom: 20px;
}

.product-info p {
  margin: 10px 0;
}

/* 商品图片 */
.product-image {
  overflow: hidden;
}

.product-image img {
  width: 100%;
  height: auto;
  display: block;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  opacity: 0;
  transition: opacity 0.5s ease-in-out;
}

.product-image img[lazy='loaded'] {
  opacity: 1;
}

/* 按钮区域 */
.action-buttons {
  margin-top: 20px;
  text-align: center;
}

/* 淡入动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
